//
//  PGTabBar.m
//  EpointFrame5
//
//  Created by Pill Gong on 14-4-17.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "PGTabBar.h"
#import "UIView+Addtions.h"

#define Line0Color COLOR(246, 246, 246)
#define Line1Color COLOR(209, 211, 214)
#define Line2Color COLOR(244, 243, 247)

#define PGTabBarBGColor COLOR(240, 239, 243)

#define ItemPadding 10.0f

@interface PGTabBar () <PGBarItemDelegate>

@property (nonatomic, strong) UIView *contentView;

@end

@implementation PGTabBar

- (id)initWithFrame:(CGRect)frame
{
    frame.size = CGSizeMake(AppWidth, BottomBarHeight);
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = PGTabBarBGColor;
        [self addContentView];
        [self addShadowLines];
    }
    return self;
}

- (void)addShadowLines {
    [self addLineWithTop:0 color:Line0Color];
    [self addLineWithTop:1 color:Line1Color];
    [self addLineWithTop:2 color:Line2Color];
}

- (void)addLineWithTop:(CGFloat)top color:(UIColor *)color {
    UIImageView *line = [UIImageView.alloc initWithFrame:CGRectMake(0, top, self.width, 1)];
    line.backgroundColor = color;
    [self addSubview:line];
}

- (void)addContentView {
    self.contentView = [UIView.alloc initWithFrame:self.bounds];
    [self addSubview:_contentView];
}

- (void)setBarItems:(NSArray *)items {
    _items = items;
    
    for (PGBarItem *item in items) {
        item.centerY = BottomBarHeight*0.5;
        item.left = ItemPadding;
        item.delegate = self;
        [_contentView addSubview:item];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    if (_items.count == 1) {
        return;
    }
    
    if (_items.count >= 2) {
        PGBarItem *item = [_items lastObject];
        item.right = AppWidth - ItemPadding;
    }
    
    if (_items.count == 3) {
        PGBarItem *midItem = [_items objectAtIndex:1];
        midItem.centerX = _contentView.width*0.5;
    }
    
    if (_items.count == 4) {
        
        CGFloat midPadding = (AppWidth - ItemPadding*2 - PGBarItemWidth*4)/3;
        
        PGBarItem *item1 = [_items objectAtIndex:1];
        item1.centerX = _contentView.width*0.5 - (PGBarItemWidth + midPadding)*0.5;
        
        PGBarItem *item2 = [_items objectAtIndex:2];
        item2.centerX = _contentView.width*0.5 + (PGBarItemWidth + midPadding)*0.5;
    }
}

#pragma mark - PGBarItemDelegate

- (void)didSelectedAtPGBarItem:(PGBarItem *)item {
    
    NSInteger index = [_items indexOfObject:item];
    
    if (_delegate && [_delegate respondsToSelector:@selector(pgTabBar:didClickedAtIndex:)]) {
        [_delegate pgTabBar:self didClickedAtIndex:index];
    }
}


@end
